from flask import g
from src.Utils.index import colored_text

class ProductDao:
    def __init__(self):
        pass
    
    def getProductList(self):
        """
        查询商品列表信息
        """
        db = g.db
        cursor = db.cursor() if db is not None else None
        sql = f"SELECT * FROM product p,productmenu pm WHERE p.typeId = pm.id"
        try:
            cursor.execute(sql)
            result = cursor.fetchall()
            cursor.close()
            print(colored_text("------查询商品列表成功------","green"))
            return result
        except:
            print(colored_text("-----查询商品列表失败-----","red"))
            return None
        finally:
            if cursor is not None:
                cursor.close()
                
    def getProductMenu(self):
        """
        查询商品分类信息
        """
        db = g.db
        cursor = db.cursor() if db is not None else None
        sql = f"SELECT * FROM productmenu"
        try:
            cursor.execute(sql)
            result = cursor.fetchall()
            cursor.close()
            print(colored_text("------查询商品分类成功------","green"))
            return result
        except:
            print(colored_text("-----查询商品分类失败-----","red"))
            return None
        finally:
            if cursor is not None:
                cursor.close()
        
    
    def insertProduct(self,name,price,oldPrice,sellCount,rating,icon,image,typeId):
        """
        插入一条商品
        
        参数
            name: 商品名称
            price: 商品价格
            oldPrice: 商品原价
            sellCount: 月销量
            rating: 好评率
            icon: 商品图标
            image: 商品图片
            typeId: 所属分类Id
        """
        db = g.db
        cursor = db.cursor() if db is not None else None
        sql = f"INSERT INTO product (name,price,oldPrice,sellCount,rating,icon,image,typeId) VALUES ('{name}',{price},{oldPrice},{sellCount},{rating},'{icon}','{image}',{typeId})"
        try:
            cursor.execute(sql)
            new_id = cursor.lastrowid
            db.commit()
            cursor.close()
            print(colored_text("------插入商品成功------","green"))
            return new_id
        except:
            print(colored_text("-----插入商品失败-----","red"))
            if db is not None:
                db.rollback()
            return None
        finally:
            if cursor is not None:
                cursor.close()
            
        